# -*- coding: utf-8 -*-
"""
-------------------------------------------------
Project Name: luffcity study project
File Name: send.py
Author: kij
Create Date: 2021/3/23
-------------------------------------------------
"""

import struct

IP_POST = ('127.0.0.1', 9992)

def send_data(conn, msg):
	"""
	发送数据
	:return:
	"""
	# 数据转成二进制
	msg2bytes = msg.encode('utf-8')
	msg_size = len(msg2bytes)
	# 拿到字节长度的四个字节 先发送
	conn.sendall(struct.pack('i', msg_size))
	# 再发送具体数据
	conn.sendall(msg2bytes)
	print('\033[0;34m发送:%s\033[0m' % msg)


def get_head_len(conn):
	"""
	读取四个字节 拿到接下来将要读取的长度
	:param conn: socket链接类
	:return:接下来将要读取的数据长度 整型数据
	"""
	bytes_list = []
	has_read_size = 0
	while has_read_size < 4:
		check = conn.recv(4 - has_read_size)
		# 如果没有数据说明断开链接
		if not check:
			return False
		has_read_size += len(check)
		bytes_list.append(check)
	header = b''.join(bytes_list)
	next_size = struct.unpack('i', header)[0]
	print('\033[0;31m数据大小:%s\033[0m' % next_size)
	return next_size


def recv_data(conn, read_size=1024):
	"""
	读取请求
	:param conn: socket链接类
	:param read_size: 默认读取的长度
	:return: 返回数据 字节数据
	"""
	next_size = get_head_len(conn)
	if not next_size:
		return False
	all_read_size = 0
	bytes_list = []
	while all_read_size < next_size:
		reads_size = read_size if next_size - all_read_size > read_size else next_size - all_read_size
		# 读取字节数据
		bytes_file = conn.recv(reads_size)
		# 添加到字节列表
		bytes_list.append(bytes_file)
		all_read_size += len(bytes_file)
	# 拼接字节数据成一个整体
	res = b''.join(bytes_list)
	print('\033[0;31m收到:%s\033[0m' % res)
	return res